/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.pg.misra.rules;

import java.util.List;
import pl.pg.misra.AST.AST;

/**
 *
 * @author Paweł
 */
public class AbstractRule {

    protected AST findNodeByType(String name, AST node) {
        AST result = null;

        if (node.getNodeType().equals(name)) {
            result = node;
        } else {
            List<AST> childrens = node.getChildrens();

            for (AST child : childrens) {
                result = findNodeByType(name, child);
            }
        }

        return result;
    }

    protected List<AST> findNodesByType(String name, AST node, List<AST> result) {
        if (node.getNodeType().equals(name)) {
            result.add(node);
        }
        
        List<AST> childrens = node.getChildrens();

        for (AST child : childrens) {
            result = findNodesByType(name, child, result);
        }
        
        return result;
    }

    protected List<AST> findNodesByTypeAndParameters(String name, AST node, List<AST> result, List<String> parameters) {
        if (node.getNodeType().equals(name)) {
            int numberOfRelatedParams = 0;

            for (String param : parameters) {
                if (node.getAttributes().contains(param)) {
                    numberOfRelatedParams++;
                }
            }

            if (numberOfRelatedParams > 0) {
                result.add(node);
            }
        }
        
        List<AST> childrens = node.getChildrens();

        for (AST child : childrens) {
            result = findNodesByTypeAndParameters(name, child, result, parameters);
        }
        
        return result;
    }

    protected AST findNodeByTypeAndParameters(String name, AST node, List<String> parameters) {
        AST result = null;

        if (node.getNodeType().equals(name)) {
            int numberOfRelatedParams = 0;

            for (String param : parameters) {
                if (node.getAttributes().contains(param)) {
                    numberOfRelatedParams++;
                }
            }

            if (numberOfRelatedParams == parameters.size()) {
                result = node;
            }
        } else {
            List<AST> childrens = node.getChildrens();

            for (AST child : childrens) {
                result = findNodeByTypeAndParameters(name, child, parameters);
            }
        }

        return result;
    }
    
    protected String buildViolationMessage(AST node, String rule, String description){
        return node.getSource() + "|" + node.getLine() + "|Violation of Rule " + rule + " in function: " + node.getAttributes().get(1) + " - " + description + ".";
    }
}
